package com.example.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ResponseUtils {
    public static void outJson(HttpServletResponse response, RestResponse ajaxResponse) {
        ServletOutputStream out = null;
        try {
            response.setStatus(HttpStatus.OK.value());
            out = response.getOutputStream();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=UTF-8");
            response.setHeader("pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            out.write(JSON.toJSONString(ajaxResponse, true).getBytes("UTF-8"));
            return;
        } catch (Exception e) {
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
